package mianshi.consumer;

import lombok.SneakyThrows;

import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Producer implements Runnable{

    private Queue<String> msg;

    private int maxSize;

    private Lock lock;

    private Condition condition;

    public Producer(Queue<String> msg, int maxSize, Lock lock, Condition condition) {
        this.msg = msg;
        this.maxSize = maxSize;
        this.lock = lock;
        this.condition = condition;
    }

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (msg.size() == maxSize) {
                condition.await();
            }

            Thread.sleep(TimeUnit.MILLISECONDS.toMillis(500));

            int val = new Random().nextInt(1000);
            System.out.println("生产消息: " + val);
            msg.add("生产消息: "+ val);
            condition.signal();

            lock.unlock();
        }
    }
}
